// SPDX-FileCopyrightText: Copyright 2025-2025 深圳市同心圆网络有限公司
// SPDX-License-Identifier: GPL-3.0-only

package image_cmd

import (
	"fmt"

	"gitcode.com/openseaotter/so_proto_gen_go.git/image_api"
	"gitcode.com/openseaotter/so_server/config"
	"gitcode.com/openseaotter/so_server/utils"
	"github.com/spf13/cobra"
)

var removeImageCmd_Force bool

var removeImageCmd = &cobra.Command{
	Use: "removeImage",
	PreRunE: func(cmd *cobra.Command, args []string) error {
		if len(args) != 2 {
			return fmt.Errorf("need param [group name] [image name]")
		}
		return nil
	},
	RunE: func(cmd *cobra.Command, args []string) error {
		cfg, err := config.ReadServerConfig()
		if err != nil {
			return err
		}
		if cfg.SuperToken == "" {
			return fmt.Errorf("miss super token in config")
		}
		conn, err := utils.ConnGrpcServer(fmt.Sprintf("127.0.0.1:%d", cfg.ServicePort))
		if err != nil {
			return err
		}
		defer conn.Close()

		client := image_api.NewImageApiClient(conn)

		groupName := args[0]
		imageName := args[1]

		res, err := client.RemoveImage(cmd.Context(), &image_api.RemoveImageRequest{
			AccessToken: cfg.SuperToken,
			GroupName:   groupName,
			ImageName:   imageName,
			Force:       removeImageCmd_Force,
		})
		if err != nil {
			return err
		}
		if res.Code != image_api.RemoveImageResponse_CODE_OK {
			return fmt.Errorf("%s", res.ErrMsg)
		}
		fmt.Println("remove image success")
		return nil
	},
}

func init() {
	removeImageCmd.Flags().BoolVar(&removeImageCmd_Force, "force", false, "force remove image")
}
